package org.example.controller;

import org.example.service.ExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 投资收益率数据导入导出控制器
 */
@RestController
@RequestMapping("/api/investment-return")
public class InvestmentReturnDataController {
    
    @Autowired
    private ExcelService excelService;
    
    /**
     * 导入Excel文件
     * @param file Excel文件
     * @param categoryType 类别类型（10+期、30+期、50+期）
     * @return 导入结果
     */
    @PostMapping("/import")
    public ResponseEntity<Map<String, Object>> importExcel(
            @RequestParam("file") MultipartFile file,
            @RequestParam("categoryType") String categoryType) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证文件
            if (file.isEmpty()) {
                result.put("success", false);
                result.put("message", "文件不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 验证文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || 
                (!originalFilename.endsWith(".xlsx") && !originalFilename.endsWith(".xls"))) {
                result.put("success", false);
                result.put("message", "文件格式不正确，请上传Excel文件(.xlsx或.xls)");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 执行导入
            int count = excelService.importExcel(file, categoryType);
            
            result.put("success", true);
            result.put("message", "导入成功");
            result.put("count", count);
            
            return ResponseEntity.ok(result);
            
        } catch (IllegalArgumentException e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(result);
        } catch (IOException e) {
            result.put("success", false);
            result.put("message", "文件读取失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "导入失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
    
    /**
     * 导出指定类别的Excel文件
     * @param categoryType 类别类型（10+期、30+期、50+期）
     * @param response HTTP响应
     */
    @GetMapping("/export/{categoryType}")
    public void exportExcel(@PathVariable String categoryType, HttpServletResponse response) {
        try {
            excelService.exportExcel(categoryType, response);
        } catch (IllegalArgumentException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            try {
                response.getWriter().write("{\"error\": \"" + e.getMessage() + "\"}");
            } catch (IOException ioException) {
                // 忽略写入错误
            }
        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try {
                response.getWriter().write("{\"error\": \"导出失败: " + e.getMessage() + "\"}");
            } catch (IOException ioException) {
                // 忽略写入错误
            }
        }
    }
    
    /**
     * 导出所有类别的Excel文件
     * @param response HTTP响应
     */
    @GetMapping("/export/all")
    public void exportAllCategoriesExcel(HttpServletResponse response) {
        try {
            excelService.exportAllCategoriesExcel(response);
        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try {
                response.getWriter().write("{\"error\": \"导出失败: " + e.getMessage() + "\"}");
            } catch (IOException ioException) {
                // 忽略写入错误
            }
        }
    }
    
    /**
     * 获取支持的类别类型
     * @return 支持的类别列表
     */
    @GetMapping("/categories")
    public ResponseEntity<Map<String, Object>> getSupportedCategories() {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("categories", new String[]{"30+金额", "60+金额", "90+金额"});
        return ResponseEntity.ok(result);
    }


    /**
     * 导入Excel文件
     * @param file Excel文件
     * @param categoryType 类别类型（10+期、30+期、50+期）
     * @return 导入结果
     */
    @PostMapping("/batchImport")
    public ResponseEntity<Map<String, Object>> batchImport(
            @RequestParam("file") MultipartFile file,
            @RequestParam("categoryType") String categoryType) {

        Map<String, Object> result = new HashMap<>();

        try {
            // 验证文件
            if (file.isEmpty()) {
                result.put("success", false);
                result.put("message", "文件不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 验证文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null ||
                    (!originalFilename.endsWith(".xlsx") && !originalFilename.endsWith(".xls"))) {
                result.put("success", false);
                result.put("message", "文件格式不正确，请上传Excel文件(.xlsx或.xls)");
                return ResponseEntity.badRequest().body(result);
            }

            // 执行导入
            int count = excelService.batchImportExcel(file, categoryType);

            result.put("success", true);
            result.put("message", "导入成功");
            result.put("count", count);

            return ResponseEntity.ok(result);

        } catch (IllegalArgumentException e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(result);
        } catch (IOException e) {
            result.put("success", false);
            result.put("message", "文件读取失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "导入失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
